﻿using BarcodeDelay.bean;
using BarcodeDelay.logHelp;
using BarcodeDelay.utility;
using JTParcrelHelper.bean;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BarcodeDelay.business
{
    public class GetUserPhoneHelperGen
    {
        private StreamWriter swb = null;
        FileStream bFile = null;
        ArrayList m_arListWeightBarcodes = new ArrayList();
        public event Action weightEvent;

        public event Action doneExpotEvent;

        public DateTime dtLastKeepAlive = System.DateTime.Now;

        ArrayList m_arListAllTask = new ArrayList();
        public Hashtable htTodayTokenCount = new Hashtable();
        private static GetUserPhoneHelperGen instance;
        public static GetUserPhoneHelperGen Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new GetUserPhoneHelperGen();
                }
                return instance;
            }
        }
        private Thread fThreadDep = null;
        public void BeginAnalyThread(ArrayList arListBarCodes, string anayType)
        {
            try
            {
                initLog();
                m_arListWeightBarcodes.Clear();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    fThreadDep.Abort();
                    System.Threading.Thread.Sleep(50);
                }
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    while (fThreadDep.ThreadState != ThreadState.Aborted)
                    {
                        //当调用Abort方法后，如果thread线程的状态不为Aborted，主线程就一直在这里做循环，直到thread线程的状态变为Aborted为止
                        Thread.Sleep(100);
                    }
                }


                m_arListWeightBarcodes = arListBarCodes;
                fThreadDep = new Thread(new ParameterizedThreadStart(parseUserMsgBoard));
                fThreadDep.Start((object)arListBarCodes);

                fThreadDep.IsBackground = true;
              

            }
            catch (Exception ex)
            {

            }
        }

        public string getValidToken(out string user)
        {
            user = "";
            string res = "";
            string todayKey = System.DateTime.Now.ToShortDateString();
            if (!htTodayTokenCount.ContainsKey(todayKey))
            {
                htTodayTokenCount[todayKey] = new Hashtable();
            }
            try
            {
                Hashtable htToken = htTodayTokenCount[todayKey] as Hashtable;
                foreach (DictionaryEntry de in StoParams.Instance.htRegInfo)
                {
                    string siteName = de.Key.ToString();
                    ArrayList arListRegBeans = (ArrayList)de.Value;
                    ArrayList arListDel = new ArrayList();
                    if(res!="")
                    {
                        break;
                    }
                    foreach (RegBean regBean in arListRegBeans)
                    {
                        string token = regBean.token;
                        string regSiteID = regBean.regSiteID;
                        string regSiteCode = regBean.regSiteCode;
                        string regWechate = regBean.regWechate;
                        
                        if(UtilityHelp.Instance.keepSiteAlive(token, regBean.regSiteName))
                        {
                            if(!htToken.ContainsKey(token))
                            {
                                htToken[token] = 1;
                                res = token;
                                user = regBean.user;
                                break;
                            }
                            else
                            {
                                int tokenCount = Convert.ToInt32(htToken[token].ToString());
                                if(tokenCount<100)
                                {
                                    res = token;
                                    user = regBean.user;
                                    break;
                                }
                            }
                        }

                    }                                     

                }
            }
            catch(Exception ex)
            {

            }
            return res;
        }

    
        public void parseUserMsgBoard(object arListBarcodes)
        {
            bool findWeight = false;
            //StoParams.Instance.htResWechat.Clear();
            string resMsg = "";
            int totalDelays = 0;
            int queryServerResTime = 0;
            int priorBarCodeCount = 0;
            ArrayList arListDepResultTmp = new ArrayList();
            try
            {
                int totalQueryCount = 0;
                ArrayList arListTmp = new ArrayList();
                RoadInfo roadInfoGen = new bean.RoadInfo();
                Hashtable htRoadMap = new Hashtable();
                ArrayList arListBarCodes = new ArrayList();
                arListBarCodes.Clear();
                DateTime dtStart = System.DateTime.Now;
                int sumQueryTime = 0;
                int avgQueryTime = 2;
                int intProcess = 0;
                string httpRes = "";
                StoParams.Instance.resMsg = "";
                ArrayList arListAllMsgBeans = new ArrayList();
                string roomid = "";
                string senderWechatID = "";

                ArrayList arListTm = (ArrayList)arListBarcodes;
                ParcelBean parcelBeanFirst = (ParcelBean)arListTm[0];
                roomid = parcelBeanFirst.roomID;
                senderWechatID = parcelBeanFirst.fromWxID;
                int curCout = arListTm.Count;
                logHelp.LogHelper.Instance.writeLog( " 取到获取手机号任务个数"+ curCout.ToString());

                
                bool isRecord = false;
                string curUser = "";
                string todayKey = System.DateTime.Now.ToShortDateString();
                string token = getValidToken(out curUser);
                if(token=="")
                {
                    logHelp.LogHelper.Instance.writeLog("生成用户信息统计报表失败 无可用token");
                    string failMsg = "{$@}" + curUser+" 无可用查询次数";
                    ReplyHelper.Instance.replySuperMsg(roomid, failMsg, "1", senderWechatID);
                    return;
                }
                foreach (ParcelBean parcelBean in (ArrayList)arListBarcodes)
                {
                    senderWechatID = parcelBean.fromWxID;
                    roomid = parcelBean.roomID;
                    if(!isRecord)
                    {
                        logHelp.LogHelper.Instance.writeLog(" fromWxID=" + parcelBean.fromWxID);
                        isRecord = true;
                    }

                    token = getValidToken(out curUser);

                    if (token == "")
                    {
                        logHelp.LogHelper.Instance.writeLog("生成用户信息统计报表失败 无可用token");
                        string failMsg = "{$@}" + curUser+" 无可用查询次数";
                        ReplyHelper.Instance.replySuperMsg(roomid, failMsg, "1", senderWechatID);
                        break;
                    }


                    string strBarCode = parcelBean.wayBill;
                    intProcess++;
                    ArrayList arListAllGXTask = new ArrayList();
                    string pickName = "";
                    string orderSource = "";
                    string curSiteToken = "";
                    CustomerBean customerBean = new CustomerBean();
                    customerBean.waybillNo = parcelBean.wayBill;
                    bool userFind = false;
                    bool isOverCount = false;               
                    UtilityHelp.Instance.getUserMsg(strBarCode, customerBean, token,out userFind,out isOverCount);
                    if(isOverCount)
                    {
                        if (htTodayTokenCount.ContainsKey(todayKey))
                        {
                            Hashtable ht = htTodayTokenCount[todayKey] as Hashtable;
                            if (ht.ContainsKey(token))
                            {
                                ht[token] =101;
                            }
                        }

                        token = getValidToken(out curUser);

                        if (token == "")
                        {
                            logHelp.LogHelper.Instance.writeLog("生成用户信息统计报表失败 无可用token");
                            string failMsg = "{$@}" + curUser + " 无可用查询次数";
                            ReplyHelper.Instance.replySuperMsg(roomid, failMsg, "1", senderWechatID);
                            break;
                        }
                        UtilityHelp.Instance.getUserMsg(strBarCode, customerBean, token, out userFind, out isOverCount);
                    }


                    if(userFind)
                    {
                        if(htTodayTokenCount.ContainsKey(todayKey))
                        {
                            Hashtable ht = htTodayTokenCount[todayKey] as Hashtable;
                            if(ht.ContainsKey(token))
                            {
                                ht[token] = Convert.ToInt32(ht[token].ToString()) + 1;
                            }
                        }
                    }
                    customerBean.tokenUser = curUser;
                    if (customerBean.receiverMobilePhone.Contains("****"))
                    {
                        Random rd2 = new Random();
                        int randomNum = rd2.Next(1000, 9999);
                        customerBean.receiverMobilePhone = customerBean.receiverMobilePhone.Replace("****", randomNum.ToString());

                    }
                                        
                    arListAllMsgBeans.Add(customerBean);

                }
                m_arListAllTask.AddRange(arListAllMsgBeans);
                if (m_arListAllTask.Count > 0)
                {
                    string sPath = "";
                   
                    bool result = UtilityExcel.Instance.GenExcelForUserPhone(m_arListAllTask, StoParams.Instance.outputDir, out sPath);
                    m_arListAllTask.Clear();
                    string response = "";
                    if (result)
                    {
                        logHelp.LogHelper.Instance.writeLog("生成用户信息统计报表成功");

                        string outputPath = UtilityHelp.Instance.uploadToAliyun(sPath, roomid);
                        response = "{$@}" + " 生成信息报表成功\r\n" + outputPath;

                    }
                    else
                    {
                        logHelp.LogHelper.Instance.writeLog("生成用户信息统计报表失败");
                        response = "{$@}" + "生成信息报表失败";
                    }
                    ReplyHelper.Instance.replySuperMsg(roomid, response, "1", senderWechatID);

                    if (doneExpotEvent != null)
                    {
                        doneExpotEvent.Invoke();
                    }
                }



                Random ran = new Random();
                //Thread.Sleep(50);



            }
            catch (Exception ex)
            {
                logHelp.LogHelper.Instance.writeLog(" 电联信息异常 " + ex.ToString());
            }
            int tiot = queryServerResTime;
           


        }






        public void stopThread()
        {
            try
            {
                ArrayList arListT = new ArrayList();
                ResultBean resultBean = new ResultBean();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    /*if (totalQueryCount > 0)
                    {
                        resultBean.countTime = totalQueryCount;

                        updateQueryCount(resultBean);
                    }*/
                    fThreadDep.Abort();
                    if (swb != null)
                    {
                        swb.Close();
                    }

                }

    
            }
            catch (Exception ex)
            {

            }
        }


        private void initLog()
        {
            try
            {
                string dir = System.Environment.CurrentDirectory;
                bFile = new FileStream(dir + "\\error.txt", FileMode.Create);
                if (swb == null)
                {
                    swb = new StreamWriter(bFile);
                    swb.WriteLine("begin");

                }
            }
            catch (Exception ex)
            {

            }

        }


    }
}
